package persistence

import (
	"errors"
	"example.com/m/v2/internal/domain/account_aggregate/entity"
	"gorm.io/gorm"
)

type MainAccountPo struct {
	gorm.Model

	Nickname string `gorm:"column:nick_name;type:varchar(32)"`
	Avatar   string `gorm:"column:avatar;type:varchar(128)"`

	Password    string `gorm:"column:password;type:varchar(16);not null"`
	PhoneNumber string `gorm:"column:phone;type:varchar(16)"`
	Email       string `gorm:"column:email;type:varchar(50)"`

	// 地址 随便写的 省和街区
	Province string `gorm:"column:province;type:varchar(16)"`
	Block    string `gorm:"column:block;type:varchar(16)"`
	UnitId   uint8  `gorm:"column:unit_id;type:uint"`
}

func (po *MainAccountPo) TableName() string {
	return "account"
}

func (po *MainAccountPo) ToEntity() (*entity.MainAccountEntity, error) {
	if po == nil {
		return nil, errors.New("nil main account po object")
	}
	return &entity.MainAccountEntity{
		Id:          po.ID,
		Nickname:    po.Nickname,
		Avatar:      po.Avatar,
		Password:    po.Password,
		PhoneNumber: po.PhoneNumber,
		Email:       po.Email,
		CreateTime:  po.CreatedAt,
		Address: entity.AddressValueObject{
			Province: po.Province,
			Block:    po.Block,
			Unit:     po.UnitId,
		},
	}, nil
}

func (po *MainAccountPo) FromEntity(entity *entity.MainAccountEntity) error {
	po.Nickname = entity.Nickname
	po.Avatar = entity.Avatar
	po.Password = entity.Password
	po.PhoneNumber = entity.PhoneNumber
	po.Email = entity.Email
	po.Province = entity.Address.Province
	po.Block = entity.Address.Block
	po.UnitId = entity.Address.Unit
	return nil
}
